package georah.map.layers
{

	import flash.display.BitmapData;
	
	import georah.carto.ExtentZ;
	import georah.carto.GISCamera;
	import georah.carto.IGISClientInfo;
	import georah.carto.PanZoom;
	import georah.map.Map;
	import georah.map.MapEvent;
	import georah.map.tools.MapTool;
	
	import mx.core.UIComponent;

	/**
	 *
	 * @author yuanm
	 */
	public class MapLayer extends UIComponent implements IGISClientInfo
	{
		public function MapLayer()
		{
			addEventListener(MapLayerEvent.OPEN, this_openHandler);
			addEventListener(MapLayerEvent.CLOSE, this_closeHandler);
		}
		
		private var _cameraDefault:PanZoom = null;

		private var _map:Map=null;

		private var _opened:Boolean=false;
		
		virtual public  function get LODs():Array
        {
        	return null;
        }

        public final function get cameraDefault():GISCamera
        {
            return _cameraDefault;
        }

        public final function set cameraDefault(value:GISCamera):void
        {
            _cameraDefault = PanZoom(value);
        }
		
		virtual public  function get cameraExtent():ExtentZ
        {
        	return null;
        }

		public final function close():void
		{
			if (!_opened)
			{
				return;
			}
			dispatchEvent(new MapLayerEvent(MapLayerEvent.CLOSE));
			_map=null;
			_opened=false;
		}

		virtual public function get enabledToolTypes():Array
		{
			return [];
		}

		public final function open(map_:Map):void
		{
			if (_opened)
			{
				return;
			}
			_map=map_;
			for each (var toolType:Class in enabledToolTypes)
			{
				var tool:MapTool=map.getTool(toolType);
				if (!tool)
				{
					tool=new toolType();
					map.enableTool(tool);
				}
			}
			dispatchEvent(new MapLayerEvent(MapLayerEvent.OPEN));
			_opened=true;
		}

		public final function get opened():Boolean
		{
			return _opened;
		}

		public final function get snapshot():BitmapData
		{
			var data:BitmapData=new BitmapData(map.width, map.height);
			data.draw(this);
			return data;
		}

		protected final function get map():Map
		{
			return _map;
		}

		virtual protected function map_changeHandler(event:MapEvent):void
		{
			if (!map)
			{
				return;
			}
			width=map.width;
			height=map.height;
		}

		virtual protected function this_closeHandler(event:MapLayerEvent):void
		{
			map.removeEventListener(MapEvent.CHANGE, map_changeHandler);
		}

		virtual protected function this_openHandler(event:MapLayerEvent):void
		{
			map.addEventListener(MapEvent.CHANGE, map_changeHandler);
			map_changeHandler(null);
		}

	}
}
